package conc;

import java.util.Random;
import java.util.concurrent.*;

public class ThreadDemo {
    private BlockingQueue<Runnable> queue;
    private ThreadPoolExecutor pool;
    private CompletionService<Integer> completionService;
    private Random random;

    public ThreadDemo() {
        queue = new ArrayBlockingQueue(10);
        pool = new ThreadPoolExecutor(4, 8, 5000, TimeUnit.MICROSECONDS, queue);
        completionService = new ExecutorCompletionService<>(pool);
        random = new Random();
    }

    public void execute() throws ExecutionException, InterruptedException {
        for (int i = 0; i < pool.getMaximumPoolSize() * 2; i++) {
            pool.execute(() -> {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("this is " + Thread.currentThread().getName());
            });
        }
        Future future=pool.submit(() ->{
            System.out.println("this is " + Thread.currentThread().getName());
            return 1;
        } );
        System.out.println("future result is " + future.get());
        FutureTask<Integer> futureTask = new FutureTask<>(() -> {
            System.out.println("this is " + Thread.currentThread().getName());
            return 2;
        });
        pool.submit(futureTask);
        System.out.println("future task result is " + futureTask.get());
        System.out.println("the number of threads is " + pool.getActiveCount());

        completionService.submit(()->{
            System.out.println("completionService,this is " + Thread.currentThread().getName());
            return 3;
        });
        System.out.println("completionService,future result is " + completionService.take().get());

        pool.shutdown();
    }
}
